package cn.fcq.basic.controller;

import cn.fcq.basic.exception.BusinessException;
import cn.fcq.basic.util.AjaxResult;
import cn.fcq.basic.util.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 分布式文件接口
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {
    //1.文件上传接口
    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart(value = "file",required = true) MultipartFile file){
        try {
            String filename = file.getOriginalFilename();
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            String path = FastdfsUtil.upload(file.getBytes(),extName);
            return AjaxResult.me().setResultObj(path);
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("保存对象失败！"+e.getMessage());
        }
    }

    @DeleteMapping
    public AjaxResult delete(@RequestParam String path){
        try {
            String pathTmp = path.substring(1);
            String group = pathTmp.substring(0,pathTmp.indexOf("/"));
            String filename = pathTmp.substring(pathTmp.indexOf("/")+1);
            FastdfsUtil.delete(group,filename);
            return AjaxResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("保存对象失败！"+e.getMessage());
        }
    }

}
